package cn.kgc.ssm.service.impl;

import cn.kgc.ssm.dto.CoursePageDTO;
import cn.kgc.ssm.entity.Course;
import cn.kgc.ssm.mapper.CourseMapper;
import cn.kgc.ssm.response.ResponseResult;
import cn.kgc.ssm.service.CourseService;
import cn.kgc.ssm.vo.CourseVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author 课工场
 * @date 2024/11/21
 * @description
 */
@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public ResponseResult coursePage(CoursePageDTO coursePageDTO) {

        PageHelper.startPage(coursePageDTO.getPage(),coursePageDTO.getLimit());
        List<CourseVO> courseVOS =  courseMapper.selectCourses(coursePageDTO.getCourseName());
        long total = new PageInfo<CourseVO>(courseVOS).getTotal();

        return ResponseResult.success().data(courseVOS).count(total);
    }

    @Override
    public ResponseResult addCoure(Course course) {

        courseMapper.insertCourse(course);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult updateCoure(Course course) {
        courseMapper.updateCourse(course);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult editCourseImg(String courseId, String fileName, String img) {

        //删除原课程图片
        File f = new File("D:/upload/course/" + img);
        if (f.exists()){
            f.delete();
        }

        courseMapper.updateCourseImg(courseId,fileName);

        return ResponseResult.success();
    }

    @Override
    public ResponseResult deleteCourse(String img) {

        // 删除图片
        File f= new File("D:/upload/course/" + img);
        if (f.exists()){
            f.delete();
        }

        courseMapper.deleteCourse(img);
        return ResponseResult.success();
    }
}
